package com.briup.estore.web.handler;

import com.briup.estore.common.result.Result;
import com.briup.estore.common.constant.ExceptionMsgEnum;
import com.briup.estore.common.exception.EstoreException;
import com.briup.estore.web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author briup-adam
 * @Date 2023/8/2 下午2:48
 * @Description
 **/

@WebServlet("/exceptionHandler")
public class ExceptionHandler extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = null;
        Throwable throwable = (Exception) req.getAttribute("javax.servlet.error.exception");
        if (throwable instanceof EstoreException) {
            EstoreException e = (EstoreException) throwable;
            result = Result.error(e.getCode(), e.getMsg());
            writeData(resp, result);
        } else {
            result = Result.error(ExceptionMsgEnum.ERROR.getCode(), ExceptionMsgEnum.ERROR.getMsg());
        }

    }
}
